package com.sservice.web.utils;

import freemarker.core.ParseException;
import freemarker.template.*;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Locale;

//import com.lowagie.text.DocumentException;
//import com.lowagie.text.pdf.BaseFont;
//import org.xhtmlrenderer.pdf.ITextRenderer;

/**
 * Created by suweiming on 2017/12/20.
 */

public class PdfHelper {

//    public static ITextRenderer getRender() throws DocumentException, IOException {
//
//        ITextRenderer render = new ITextRenderer();
//        ClassPathResource songTi = new ClassPathResource("fonts/simsun.ttf");
//        ClassPathResource kaiTi = new ClassPathResource("fonts/simkai.ttf");
//        org.xhtmlrenderer.pdf.ITextFontResolver fontResolver = render.getFontResolver();
//        String path = songTi.getURL().toString();
//        String path_kaiti = kaiTi.getURL().toString();
//        fontResolver.addFont(path.replace("file:" + (!Constants.isDebug ? "" : "/"), ""), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
////        fontResolver.addFont("C:/Windows/Fonts/simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//        fontResolver.addFont(path_kaiti.replace("file:" + (!Constants.isDebug ? "" : "/"), ""), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//
//        return render;
//    }

    //获取要写入PDF的内容
    public static String getPdfContent(String ftlPath, String ftlName, Object o) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
        return useTemplate(ftlPath, ftlName, o);
    }

    //使用freemarker得到html内容
    public static String useTemplate(String ftlPath, String ftlName, Object o) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {

        String html = null;

        Template tpl = getFreemarkerConfig(ftlPath).getTemplate(ftlName);
//        tpl.setEncoding("UTF-8");

        StringWriter writer = new StringWriter();
        tpl.process(o, writer);
        writer.flush();
        html = writer.toString();
        return html;
    }

    /**
     * 获取Freemarker配置
     *
     * @param templatePath
     * @return
     * @throws IOException
     */
    private static Configuration getFreemarkerConfig(String templatePath) throws IOException {
        Configuration config = new Configuration();
        File file = new File("/" + templatePath);
        config.setDirectoryForTemplateLoading(file);
        config.setEncoding(Locale.CHINA, "utf-8");
        return config;
    }

    /**
     * 获取类路径
     *
     * @return
     */
    public static String getPath() {
        return PdfHelper.class.getResource("").getPath().substring(1);
    }


    public static void main(String[] arg) throws IOException {
        File fi = new File("H:/java/marketingplatform/target/marketingplatform/WEB-INF/classes");
//        System.out.print(fi.getCanonicalPath());
    }
}
